<template>
  <div class="fixed w-full h-full left-0 top-0 bg-mask-5 flex justify-center items-center z-10">
    <div class="recharge w-350px h-335px flex flex-col items-center relative rounded-6px">
      <div class="color-word text-20px mt-20px leading-28px font-bold tracking-wider">
        {{ props.level?.name }}
      </div>
      <div class="w-139px h-139px mt-16px rounded-4px" style="border: 1px solid #eee">
        <QRCodeVue3 :value="payUrl" style="padding: 6px" />
      </div>
      <div class="text-14px color-word leading-21px h-23px">请使用微信扫码支付</div>
      <div class="flex items-center mt-13px">
        <div><img :src="RechargeTipIcon" alt="" /></div>
        <div class="text-14px h-21px leading-21px" style="color: #fedd32">
          开通享受{{ props.level?.name }}全部权益和礼包
        </div>
      </div>
      <div class="flex items-end mt-12px">
        <div class="text-14px" style="color: #5c5c5c">应付：</div>
        <div class="text-24px">￥{{ props.level.price }}元</div>
      </div>
      <div class="absolute -right-24px -top-24px z-11 cursor-pointer" @click="close">
        <img :src="CloseIcon" alt="" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted } from 'vue'
import RechargeTipIcon from '@renderer/assets/rechargeTip.svg'
import CloseIcon from '@renderer/assets/closeLogin.svg'
import useHttp from '@renderer/utils/http'
import dayjs from 'dayjs'
import QRCodeVue3 from 'qrcode-vue3'

const payUrl = ref<any>(null)
const props = defineProps({
  level: {
    type: Object,
    required: true
  },
  value: {
    type: Boolean,
    default: false
  }
})
const emits = defineEmits(['update:value', 'open-success'])

const orderNo = ref<string | null>(null)
let timer: number | null = null
const repeatPayResult = () => {
  timer = setInterval(async () => {
    const { data: res } = await useHttp(`/wx/payResult?order=${orderNo.value}`).get().json()
    if (res.value.code === 200) {
      clearInterval(timer as number)
      timer = null
      emits('open-success')
    }
  }, 1000)
}
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})
watch(
  () => props.level?.id,
  async (v) => {
    if (v) {
      orderNo.value = `vip` + dayjs().format('YYYYMMDDHHmmssSSS')
      const { data: res } = await useHttp('/wx/payUrl')
        .post({
          orderNo: orderNo.value,
          amount: props.level.price,
          name: `云游电竞${props.level.name}`
        })
        .json()
      if (res.value.code === 200) {
        const { code_url, return_code } = res.value.data
        if (return_code === 'SUCCESS') {
          payUrl.value = code_url
          repeatPayResult()
        }
      }
    }
  },
  {
    immediate: true
  }
)

const close = () => {
  emits('update:value', false)
}
</script>

<style scoped>
.recharge {
  background: url('@renderer/assets/rechargeCodeWrapper.svg');
}
</style>
